//
//  UIColor.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2024/12/25.
//
import SwiftUI
extension Color {
    static func hex(_ hex: String) -> Color {
        let cleanedHex = hex.hasPrefix("#") ? String(hex.dropFirst()) : hex
        var rgb: UInt64 = 0
        Scanner(string: cleanedHex).scanHexInt64(&rgb)
        let r = CGFloat((rgb >> 16) & 0xff) / 255
        let g = CGFloat((rgb >> 8) & 0xff) / 255
        let b = CGFloat(rgb & 0xff) / 255
        return Color(red: r, green: g, blue: b)
    }
    
    func toHex() -> String? {
        // Convert the Color to a UIColor
        let uiColor = UIColor(self)
        
        // Extract RGB components
        guard let components = uiColor.cgColor.components, components.count >= 3 else {
            return nil
        }
        
        let r = components[0]
        let g = components[1]
        let b = components[2]
        
        // Format the RGB values as a hex string
        let hexString = String(format: "#%02lX%02lX%02lX",
                               lround(Double(r * 255)),
                               lround(Double(g * 255)),
                               lround(Double(b * 255)))

        return hexString
    }
    
    
    
    static func uiColor(swiftColor: Color) -> UIColor {
        // 获取 Color 的 CGColor，并桥接到 UIColor
        guard let cgColor = swiftColor.cgColor else {
            return UIColor.black // 默认返回黑色或其他适当的颜色
        }
        return UIColor(cgColor: cgColor)
    }
}
